using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace SLIITPro.Core
{
    public class SqlConnections
    {
        public SqlConnection Connection;
        public SqlDataReader DataReader;
        public SqlCommand Command;
        
        public void CloseConn()
        {
            if (Connection != null)
            {
                if (Connection.State == ConnectionState.Open)
                {
                    Connection.Close();
                }
                Connection.Dispose();
            }
        }

        public SqlConnection CreateConn()
        {
            if (Connection == null) { Connection = new SqlConnection(); }
            if (string.IsNullOrEmpty(Connection.ConnectionString))
            {
                try
                {
                    Connection.ConnectionString = String.Format("Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;{0}", CoreSettings.MySqlConnectionString);
                    Connection.Open();
                }

                catch (Exception)
                {
                    try
                    {
                        if (Connection.State != ConnectionState.Closed)
                        {
                            Connection.Close();
                        }
                        Connection.ConnectionString = string.Format("Pooling=false;Connect Timeout=45;{0}", CoreSettings.MySqlConnectionString);
                        Connection.Open();
                    }
                    catch (Exception)
                    {
                        throw new Exception("Database Connection was not estabilished");
                    }
                }
                return Connection;
            }

            if (Connection.State != ConnectionState.Open)
            {
                try
                {
                    Connection.ConnectionString = String.Format("Min Pool Size=5;Max Pool Size=40;Connect Timeout=4;{0}", CoreSettings.MySqlConnectionString);
                    Connection.Open();
                }
                catch (Exception)
                {
                    if (Connection.State != ConnectionState.Closed)
                    {
                        Connection.Close();
                    }
                    Connection.ConnectionString = String.Format("Pooling=false;Connect Timeout=45;{0}", CoreSettings.MySqlConnectionString);
                    Connection.Open();
                }
            }
            return Connection;
        }
    }
}